from django.shortcuts import render
from django.http import HttpResponse
from myadmin.models import *



# 进行分类及商品查询
def loadType():
    # 获取所有的顶级分类及子类和子类商品
    ob = Types.objects.filter(pid=0)

    for v in ob:
        v.sub = Types.objects.filter(pid=v.id)
        for vv in v.sub:
            vv.glist = Goods.objects.filter(typeid=vv.id)
    return ob;
# Create your views here.
def index(request):
    
    '''
    [
        {
            id:1,
            name:服装,
            sub:[
                    {
                        id:4,
                        name:'男装',
                        glist:[
                                {id:1,title:'风流倜傥衣',price:999.00},
                                {id:2,title:'风流倜傥裤',price:99.00},
                            ]

                    },
                    {id:5,name:'女装'},
                ]
        },
        {
            id:2,
            name:手机,
            sub:[
                {id:6,name:'小米'},
                {id:7,name:'锤子'},
                {id:8,name:'诺基亚'},
            ]
        },
        {   id:3,
            name:电脑,
            sub:[
                {id:9,name:'苹果'},
                {id:9,name:'小米'},
                {id:9,name:'联想'},
            ]
        },
    ]
    '''
    # 获取所有的顶级分类及子类和子类商品

    # 分配数据
    context = {'types':loadType()}


    return render(request,'myweb/index.html',context)


# 网站列表页
def list(request,tid):

    # 根据当前的tid获取所有的商品信息 
    ob = Types.objects.filter(pid = tid)
    for v in ob:
        v.glist = Goods.objects.filter(typeid = v.id)


    '''
        [
            {
                id:2,
                name:'男装',
                glist:[
                    {id:1,title:'风衣',price:999},
                    {id:2,title:'裤',price:999}
                ]
            },
            {
                id:3,
                name:'女装',
                glist:[
                    {id:1,title:'女风衣',price:999},
                    {id:2,title:'女裤',price:999}
                ]
            }
        ]

    '''

    # 分配数据
    context = {'glist':ob,'types':loadType()}

    # 解析模板
    return render(request,'myweb/list.html',context)


# 网站详情页
def ginfo(request,gid):
    # 根据商品id获取商品信息
    ginfo = Goods.objects.get(id = gid)

    # 分配数据
    context = {'ginfo':ginfo,'types':loadType()}

    # 解析模板
    return render(request,'myweb/ginfo.html',context)


# 加入购物车
def cartadd(request):
    # 商品数据
    g = Goods.objects.get(id=request.POST['gid'])
    goods = {}
    goods['gid'] = request.POST['gid']
    goods['num'] = int(request.POST['num'])
    goods['title'] = g.title
    goods['price'] = g.price
    goods['picname'] = g.picname
    # 购物车数据
    cart = request.session.get('cart',{})
    # 判断当前商品是否已经存在购物车
    if request.POST['gid'] not in cart:
        # 把商品数据添加到cart里
        cart[request.POST['gid']] = goods
    else:
        cart[request.POST['gid']]['num'] += int(request.POST['num'])

    # 把购物车数据(cart) 存入session中
    request.session['cart'] = cart
    # {'2':{gid:2,num:3}}
    return HttpResponse('<script>alert("加入购物车成功");location.href="/cartshow";</script>')



# 购物车列表
def cartshow(request):
    return render(request,'myweb/cart.html')

# 购物车商品删除
def cartdel(request):
    # 获取session中的购物车数据
    cart = request.session['cart']
    # 删除
    cart.pop(request.GET['gid'])
    # {1:{},2:{},3:{}}
    # 重新把cart数据存入session
    request.session['cart'] = cart

    return HttpResponse('<script>alert("商品删除成功");location.href="/cartshow";</script>')
    # return HttpResponse(request.GET['gid'])

# 购物车数量更新
def cartedit(request):
    gid = request.GET['gid']
    num = int(request.GET['num'] )

    # 判断num是否小于1
    if num < 1:
        return HttpResponse('<script>alert("购买数量最低为1");location.href="/cartshow";</script>')

    # 获取session中的购物车数据
    cart = request.session['cart']
    
    # 修改数据
    cart[gid]['num'] = num

    # 重新把cart数据存入session
    request.session['cart'] = cart
    return HttpResponse('<script>alert("数量更新成功");location.href="/cartshow";</script>')


# 清空购物车
def cartclear(request):
    request.session['cart'] = {}
    return HttpResponse('<script>alert("购物车已清空");location.href="/cartshow";</script>')


# 确认订单
def orderadd(request):
    # 获取所有已选中的商品id
    ids = request.POST['ids']

    # 转成列表
    ids = ids.split(',')

    # 在购物车中获取商品信息
    cart = request.session.get('cart',{})
    data = []
    total = 0
    subnum = 0
    for v in ids:
        data.append(cart[v])
        total+= cart[v]['num']*cart[v]['price']
        subnum += cart[v]['num']
    # 讲数据添加到定单变量中
    order = {'goods':data,'total':total,'subnum':subnum}

    # 把订单信息存入session
    request.session['order'] = order

    return render(request,'myweb/order/index.html',order)



# 创建订单
def ordercreate(request):
    # 把订单数据加入到数据库,并显示支付页面
    # 添加订单信息  # 收货信息, 表单中
    ob = Orders()
    ob.uid = request.session['VipUser']['uid']
    ob.linkman = request.POST['uname']
    ob.address = request.POST['address']
    ob.code = request.POST['pcode']
    ob.phone = request.POST['phone']
    ob.total = request.POST['total']
    ob.status = 0
    ob.save()

    # 添加订单详情信息 购买的商品信息 session
    order = request.session['order']['goods']


    for v in order:
        # print(v,v['gid'])
        db = Odetail()
        db.orderid = ob.id
        db.goodsid = v['gid']
        db.title = v['title']
        db.price = v['price']
        db.num = v['num']
        db.picname = v['picname']
        db.save()
        # 清除购物车中已经购买的商品
        # 读取购物车信息
        cart = request.session.get('cart',{})
        cart.pop(v['gid'])
        # 重新存入session
        request.session['cart'] = cart;


  

    # 跳转到支付模块
    return HttpResponse('<script>alert("订单创建成功,请支付");location.href="/buy/'+str(ob.id)+'";</script>')

    # 跳转到个人中心,我的订单

# buy
def buy(request,orderid):
    # 获取订单,生成支付页面
    ob = Orders.objects.get(id = orderid)

    # 分配数据,展示支付页面
    context = {'order':ob}

    return render(request,'myweb/order/buy.html',context)


# 我的订单
def myorder(request):
    # 根据用户id获取用户的所有订单信息
    uid = request.session['VipUser']['uid']
    # 获取当前用户的订单信息
    ob = Orders.objects.filter(uid=uid)
    # 根据订单获取当前订单的详情信息
    for x in ob:
        x.sub = Odetail.objects.filter(orderid = x.id)

    # 分配数据
    context = {'myorders':ob}

    # 解析模板
    return render(request,'myweb/order/myorder.html',context)




# 注册页面
def register(request):
    # 加载模板
    return render(request,'myweb/login/register.html')

# 执行注册
def doregister(request):
    # 首先判断验证码填写是否正确
    if request.session['verifycode'] != request.POST['code'].upper():
        return HttpResponse('<script>alert("验证码不正确");location.href="/register";</script>')

    try:
        from django.contrib.auth.hashers import make_password, check_password
        ob = Users()
        ob.username = request.POST['username']
        ob.phone = request.POST['phone']
        # 密码
        ob.password = make_password(request.POST['password'], None, 'pbkdf2_sha256')
        ob.save()

        # 如果注册成功直接登录
        request.session['VipUser'] = {'uid':ob.id,'uname':ob.username}
        return HttpResponse('<script>alert("注册成功");location.href="/";</script>')
    except:
        return HttpResponse('<script>alert("注册失败,请联系管理员");location.href="/register";</script>')


# 登录页面
def login(request):
    # 加载模板
    return render(request,'myweb/login/login.html')

# 执行登录
def dologin(request):
    # 首先判断验证码填写是否正确
    if request.session['verifycode'] != request.POST['code'].upper():
        return HttpResponse('<script>alert("验证码不正确");location.href="/login";</script>')

    try:
        # 判断用户名是否存在,
        ob = Users.objects.get(username = request.POST['username'])
       
        # 如果存在,判断密码是否正确
        from django.contrib.auth.hashers import make_password, check_password
        if check_password(request.POST['password'],ob.password):
            # 如果密码正确,把用户信息写入session,来标记用户的登录行为
            request.session['VipUser'] = {"uid":ob.id,"uname":ob.username}
            # 跳转到首页
            return HttpResponse('<script>alert("登录成功");location.href="/";</script>')
        else:
            return HttpResponse('<script>alert("用户名或密码错误");location.href="/login";</script>')
    except:
        return HttpResponse('<script>alert("用户名或密码错误");location.href="/login";</script>')
